package com.sanji.pay.allinpay.service;

import com.sanji.pay.allinpay.entity.AllinPay;
import com.sanji.pay.allinpay.repository.AllinPayRepository;
import com.sanji.pay.common.utils.DateUtil;
import com.sanji.pay.pay.dto.PayDeal;
import com.sanji.pay.pay.entity.PayOrder;
import com.sanji.pay.pay.service.PayOrderService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.TreeMap;

/**
 * Created by cbh on 2017/8/26.
 */
@Service
public class AllinPayServiceImpl implements AllinPayService {
  private static final Logger logger = Logger.getLogger(AllinPayServiceImpl.class);

  @Autowired
  private PayOrderService payOrderService;
  @Autowired
  private AllinPayRepository allinPayRepository;

  @Override
  public AllinPay findByPayNum(String payNumber) {
    return allinPayRepository.findByPayNum(payNumber);
  }

  @Override
  public AllinPay save(AllinPay allinPay) {
    return allinPayRepository.save(allinPay);
  }

  @Override
  public AllinPay saveAlliPay(TreeMap<String, String> params,AllinPay allinPay) {
    //保存支付信息
    allinPay = allinPay==null? new AllinPay() : allinPay;
    allinPay.setTrxStatus(params.get("trxstatus"));
    allinPay.setPayTime(DateUtil.getDateStrToDate(params.get("paytime"),"yyyyMMddHHmmss"));
    allinPay.setTrxAmt(Integer.valueOf(params.get("trxamt")));
    logger.info("查看是否保存了签名信息" + allinPay.getTrxSign());
    allinPay.setTrxSign(allinPay.getTrxSign());
    PayOrder payOrder = payOrderService.findByPayNumber(allinPay.getPayNum());
    payOrder.setStatus(PayOrder.PayStatus.SUCCESS);
    if("A01".equals(allinPay.getTrxCode())){
      payOrder.setDealType("AliPay");
    }else{
      payOrder.setDealType("WeChat");
    }
    payOrder.setPayment(0);
    payOrder.setPayTime(DateUtil.getDateStrToDate(params.get("paytime"),"yyyy-MM-dd HH:mm:ss"));
    payOrderService.save(payOrder);
    return save(allinPay);
  }

  /**
   * 回调给商户
   * @param allinPay
   */
  @Override
  public void callbacktoMerchant(AllinPay allinPay) {
   try {
    PayOrder payOrder = payOrderService.findByPayNumber(allinPay.getPayNum());
    PayDeal payDeal = new PayDeal();
    payDeal.setOrderNum(payOrder.getOrderNum());
    payDeal.setTotalCost(payOrder.getAmount());
    payDeal.setDealFee(allinPay.getTrxAmt());
    payDeal.setDealState(allinPay.getTrxStatus());
    payDeal.setHmac(allinPay.getTrxSign() == null ? "" : allinPay.getTrxSign());
    payDeal.setDealId(allinPay.getTrxId());
    payDeal.setDealType("XS");
    payDeal.setPayTime(allinPay.getPayTime() == null ? new Date() : allinPay.getPayTime());
    payDeal.setPayType("gateway");
    payDeal.setPayee("");
    payDeal.setBankCardNo("");
    payDeal.setBankCardName("");
    payDeal.setPayNum(allinPay.getPayNum());

    payOrderService.callbackToClient(payDeal,payOrder.getSourceType());
  } catch(Exception e){
    logger.info("订单推送三际商城失败===========" + e);
  }
  }
}
